﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SuperSocket.Channel;
using SuperSocket.Server;

namespace Example.Modbus.Kernel;

public class RtuSession (IConfiguration configuration) : AppSession {
    private Timer? _timer;
    public IConfiguration Configuration { get; } = configuration;
    public byte Address { get; set; }

    protected override async ValueTask OnSessionConnectedAsync()
    {
        await SendIdRequsetAsync();
    }

    protected override async ValueTask OnSessionClosedAsync(CloseEventArgs e)
    {
        if (_timer != null)
        {
            await _timer.DisposeAsync();
        }
    }

    /// <summary>
    /// 获取设备ID，XPH私有协议，设备在modbus模式下依然支持，00 为广播地址，在地址未知的情况下也可以通讯
    /// </summary>
    public async ValueTask SendIdRequsetAsync()
    {
        byte[] message = { 0x00, 0x20, 0x00, 0x68 };
        await Channel.SendAsync(message);
        Logger.LogDebug("{RemoteEndPoint}下发{message}, 读设备ID", RemoteEndPoint, BitConverter.ToString(message).Replace("-", " "));
    }
    
    public void BeginReadData()
    {
        if (_timer != null)
        {
            return;
        }
        var cfg = Configuration.GetSection("DateRequset");
        if (!int.TryParse(cfg["Timespan"], out int timespan))
        {
            timespan = 15;
        }
        _timer = new Timer(async state =>
        {
            await SendDataRequsetasync();
        }, null, TimeSpan.Zero, TimeSpan.FromMinutes(timespan));
    }

    /// <summary>
    /// 获取设备数据，参考《自动气象站通讯协议_平台》气象站标准 MODBUS 通讯协议(1).获取 16 通道数据
    /// </summary>
    /// <param name="id">设备地址，有效范围 0-254，0 为广播地址</param>
    public async Task SendDataRequsetasync()
    {
        byte[] message = { Address, 0x03, 0x00, 0x00, 0x00, 0x10 };
        byte[] crc = message.CRC16();// Util.CRC16(message);

        byte[] data = new byte[message.Length + crc.Length];
        message.CopyTo(data, 0);
        crc.CopyTo(data, message.Length);

        await Channel.SendAsync(data);
        Logger.LogDebug("{RemoteEndPoint}:{Address} - value: {values}, Modus模式获取设备传感器数据", RemoteEndPoint, Address, BitConverter.ToString(data).Replace("-", " "));
    }
}